import pandas as pd
from sqlalchemy import create_engine
from utils.config import get_config


def history_price_database():
    """
    将历史价格数据写入数据库
    """
    # 创建 ConfigParser 对象
    config = get_config('../../server_config.ini')

    # 读取CSV文件
    df = pd.read_csv(f'../../data_csv/history_price/history_price.csv')

    df['product_id'] = df['product_id'].astype(str)
    df['date_time'] = pd.to_datetime(df['date_time'], errors='coerce')
    df['date_time'] = df['date_time'].dt.strftime('%Y-%m-%d %H:%M:%S')  # 转换日期时间格式

    # 连接到PostgreSQL数据库
    engine = create_engine('postgresql://'+config['user']+':'+config['password']+'@'+
                           config['host']+':'+config['port']+'/'+config['database'])

    # 将数据写入数据库
    # 分批写入数据库
    for i in range(0, len(df), 1000):
        df[i:i+1000].to_sql('history_price', engine, if_exists='append', index=False)

